package com.youxin.chat.user.mq.consumer.message;

import com.alibaba.fastjson.JSONObject;

import com.youxin.base.MsgDto;
import com.youxin.common.constant.MsgTypeEnum;
import com.youxin.chat.user.manager.ImManager;
import com.youxin.chat.user.mapper.UserInfoMapper;
import com.youxin.chat.user.model.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Component
public class NicknameProtectResolver implements MsgResolver {
    private Logger logger = LoggerFactory.getLogger(NicknameProtectResolver.class);

    @Resource
    private ImManager imManager;

    @Resource
    private UserInfoMapper userInfoMapper;
    @Override
    public Boolean supportType(String type) {
        return MsgTypeEnum.NICKNAME_PROTECT.getType().equalsIgnoreCase(type);
    }

    @Override
    public void doResolve(MsgDto msgDto) {
        logger.info("群成员昵称保护设置，data={}", JSONObject.toJSONString(msgDto));
        try {
            JSONObject jsonObject = JSONObject.parseObject(msgDto.getData());
            String groupId = jsonObject.getString("groupId");
            String nicknameProtect = jsonObject.getString("nicknameProtect");
            String userNo = jsonObject.getString("userNo");
            Map<String, Object> dataMap = new HashMap<>();
            UserInfo userInfo =userInfoMapper.selectByUserNo(userNo);
            dataMap.put("operatorNickname", Optional.ofNullable(userInfo.getNickName()).orElse(""));
            if (nicknameProtect.equals("0")) {
                String msg = "群成员昵称保护模式已开启，只有群主或管理员设置群内昵称";
                imManager.sendGroupNoticeMsg( imManager.getSystemNo(), groupId, userNo,  msg, "nicknameProtectOpen", "");
                logger.info("群成员昵称保护开启设置，data={}", JSONObject.toJSONString(msgDto));
            } else if (nicknameProtect.equals("1")) {
                String msg = "群成员昵称保护模式已关闭,群成员可设置群内昵称";
                imManager.sendGroupNoticeMsg( imManager.getSystemNo(), groupId, userNo,  msg, "nicknameProtectClose", "");
                logger.info("群成员昵称保护关闭设置，data={}", JSONObject.toJSONString(msgDto));
            }

        } catch (Exception e) {
            logger.error("群成员昵称保护设置，error=", e);
        }
    }
}
